<template>
  <div class="wraper">
    <div class="top">
      <el-button type="primary" size="small" @click="openFile">选择图片</el-button>
      <el-button type="primary" style="margin-left: 10px" size="small" @click="copy">复制结果</el-button>
      <el-button type="warning" style="margin-left: 10px" size="small" @click="text = null">清空结果</el-button>

    </div>
    <div class="bot" v-if="loading">
      <ElProgress :text-inside="true" :stroke-width="16" :percentage="percentage"></ElProgress>
    </div>
    <el-input
      v-model="text"
      placeholder="识别结果"
      :autosize="{ minRows: 10, maxRows: 10 }"
      show-word-limit
      type="textarea"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { createWorker } from 'tesseract.js'
import { ElProgress } from 'element-plus'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/progress/style/css'

const text = ref()
const percentage = ref(0)
const loading = ref(false)

const openFile = async () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = 'image/*'
  fileInput.click()

  fileInput.addEventListener('change', async (event) => {
    loading.value = true
    const file = event.target.files[0]
    try {
      const worker = await createWorker('eng+chi_sim', 1, {
        logger: (m) => {
          console.log(m)
          if (m.status === 'recognizing text') {
            percentage.value = parseInt(m.progress * 100)
          }
        }
      })
      const ret = await worker.recognize(file)
      text.value = ret.data.text

      setTimeout(() => {
        loading.value = false
        percentage.value = 0
      }, 500)
      await worker.terminate()
    } catch (error) {
      console.error('识别失败:', error)
      text.value = '识别失败，请重试'
      percentage.value = 0
    }
  })
}
const copy = () => {
  if (text.value == null) {
    ElMessage({
      message: '请先选择图片！',
      type: 'warning'
    })
  } else {
    navigator.clipboard.writeText(text.value)
    ElMessage({
      message: '复制成功！',
      type: 'success'
    })
  }
}
</script>

<style scoped lang="less">
.wraper {
  width: 100vw;
  height: 100vh;
  padding: 10px;
  background-color: #999;
  -webkit-app-region: no-drag;
  display: flex;
  flex-direction: column;
  .top {
    height: 40px;
  }
  .bot{
    margin: 5px 0;
  }
}
</style>
